package com.mall.manager.authority.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.WebUtils;

import com.mall.common.attributes.CommonAttributes;
import com.mall.common.entity.PowerInfo;
import com.mall.common.entity.ShiroUser;
import com.mall.common.token.UserAuthenticationToken;
import com.mall.manager.authority.service.PartPowerService;
import com.mall.manager.authority.service.UsersPartService;
import com.mall.manager.authority.service.UsersService;
import com.mall.untils.DateUtils;
import com.mall.untils.Page;
import com.mall.untils.StringUtil;

/**
 * 用户信息列表
 * @author liugb
 * @date 2016 7 7
 */
@SuppressWarnings("unchecked")
@Controller
@RequestMapping("/manager")
public class UsersController {
	Logger logger = LoggerFactory.getLogger(UsersController.class);
	
	@Resource 
	UsersService usersService;
	@Resource
	UsersPartService usersPartService;
	@Resource
	PartPowerService partPowerService;
	

	@RequestMapping(value = "/indexMain")
	public String main(HttpServletRequest request){
		ShiroUser user  = (ShiroUser) request.getSession().getAttribute(CommonAttributes.SESSION_ATTRIBUTE_NAME);
		if(user!=null){
			return "common/index";
		}
		return "redirect:/manager/manager_tusers_login";
	}
	
	/**
	 * 登陆方法
	 * @param request
	 * @param modelMap
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/manager_tusers_login")
	public String manager_tusers_login(HttpServletRequest request, ModelMap modelMap,HttpServletResponse response) {
		
		try{
	    	Map<String, Object> map = usersService.manager_find_user(WebUtils.getParametersStartingWith(request, ""));
	    	if(map!=null&&map.size()>0){
	    		List<Map<String,Object>> userPart = usersPartService.findUserPart(map);
	    		//判断该角色拥有的权限列表，无权限不给登录
	    		if(userPart!=null&&userPart.size()>0){
	    			Integer userId = MapUtils.getInteger(map, "id");
	    			String name = MapUtils.getString(map, "name");
	    			String account = MapUtils.getString(map, "account");
	    			String password = MapUtils.getString(map, "password");
	    			ShiroUser user = new ShiroUser(userId, account, name);
	    			List<PowerInfo> one = new ArrayList<PowerInfo>();
	    			List<PowerInfo> two = new ArrayList<PowerInfo>();
	    			List<PowerInfo> three = new ArrayList<PowerInfo>();
	    			//shiro login
	    			List<PowerInfo> power = partPowerService.findRolePermission(userId,null,null);
	    			if(power!=null&&power.size()>0){
		    			for (PowerInfo powerInfo : power) {
		    				if(powerInfo.getLevel()==1){
		    					one.add(powerInfo);
		    				}
		    				if(powerInfo.getLevel()==2){
		    					two.add(powerInfo);
		    				}
		    				if(powerInfo.getLevel()==3){
		    					three.add(powerInfo);
		    				}
						}
		    			UserAuthenticationToken token = new UserAuthenticationToken(userId, name, password, power, null);
		    			Subject subject = SecurityUtils.getSubject();
		    			subject.login(token);
		    			HttpSession session = request.getSession();
		    			session.setAttribute("account", account);
		    			session.setAttribute("userName",name);
		    			session.setAttribute("power", power);
		    			session.setAttribute(CommonAttributes.SESSION_ATTRIBUTE_NAME, user);
		    			session.setAttribute(CommonAttributes.SESSION_ATTRIBUTE_ONE,one);
		    			session.setAttribute(CommonAttributes.SESSION_ATTRIBUTE_TWO,two);
		    			session.setAttribute(CommonAttributes.SESSION_ATTRIBUTE_THREE,three);
		    			return "common/index";
	    			}
	    		}
	    		logger.info("当前账号："+MapUtils.getString(map, "name")+"的角色权限不足！");
	    	}
		}catch(Exception e){
			logger.info("登录异常："+e.toString());
		}
		return "common/login";
	}
	
	/**
	 * 退出登录
	 * @param request
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/logout")
	public ModelAndView logout(HttpServletRequest request, HttpSession session) {
		try {
			//清空用户信息
			session.removeAttribute(CommonAttributes.SESSION_ATTRIBUTE_NAME);
			//清空三级菜单
			session.removeAttribute(CommonAttributes.SESSION_ATTRIBUTE_THREE);
			//清空二级菜单
			session.removeAttribute(CommonAttributes.SESSION_ATTRIBUTE_TWO);
			//清空一级菜单
			session.removeAttribute(CommonAttributes.SESSION_ATTRIBUTE_NAME);
			Subject subject = SecurityUtils.getSubject();
			subject.logout();
		} catch (Exception e) {
			logger.info("在"+DateUtils.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss")+"退出系统出现异常："+e.toString());
		}
		return new ModelAndView("redirect:/manager/manager_tusers_login"); 
	}
	
	   /**
	    * 用户信息列表
	    * @param request
	    * @param response
	    * @param modelMap
	    * @return
	    */
	  @RequestMapping(value = "/manager_tusers_list")
	    public String manager_tusers_list(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
	    	Page page=usersService.manager_tusers_list(request);
	    	Map<String,Object> paraMap = WebUtils.getParametersStartingWith(request, "");
			String name = MapUtils.getString(paraMap, "name");
			if(!StringUtils.isEmpty(name)){
	    		modelMap.addAttribute("name",StringUtil.getByteToString(name));
	    	}
	     	if(null!=page){
		     	modelMap.addAttribute("manager_tusers_list", (List<Map<String,Object>>)page.getResult());
		     	int totalpagecount = page.getTotalPageCount();
		     	modelMap.addAttribute("totalpagecount", totalpagecount);
		     	int currentpageno = page.getCurrentPageNo();
		     	modelMap.addAttribute("currentpageno", currentpageno);
		     	int previouspage = page.getCurrentPageNo() <= 1 ? 1 : page
						.getCurrentPageNo() - 1;
		     	modelMap.addAttribute("previouspage", previouspage);
		     	int nextpage = page.getCurrentPageNo() >= page.getTotalPageCount() ? page
						.getTotalPageCount() : page.getCurrentPageNo() + 1;
				modelMap.addAttribute("nextpage", nextpage);
				List<Integer> showNumList = page.getShowNumList();
				modelMap.addAttribute("pagenumlist", showNumList);
	     	}
	    	return "users/user_list";
	    } 
	  /**
	   * 编辑页面跳转
	   * @param request
	   * @param response
	   * @param modelMap
	   * @return
	   */
	  @RequestMapping(value = "/tusers_edit")
	    public String tusers_edit(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
	    	Map<String,Object> paraMap = WebUtils.getParametersStartingWith(request, "");
	    	int id = MapUtils.getIntValue(paraMap, "id");
	    	if(id!=0){
	    		Map<String, Object> map = usersService.findById(id);
	    		modelMap.addAttribute("id", id);
	    		modelMap.addAttribute("account", map.get("account"));
	    		modelMap.addAttribute("password", map.get("password"));
	    		modelMap.addAttribute("name", map.get("name"));
	    		modelMap.addAttribute("age", map.get("age"));
	    		modelMap.addAttribute("sex", map.get("sex"));
	    		modelMap.addAttribute("phone", map.get("phone"));
	    		modelMap.addAttribute("email", map.get("email"));
	    	}else{
	    		modelMap.addAttribute("account", "");
	    		modelMap.addAttribute("password", "");
	    	}
	    	return "users/user_add";
	    } 
	    /**
	     * 删除用户表
	     * @param request
	     * @param response
	     * @param modelMap
	     * @return
	     */
	    @RequestMapping(value = "/manager_del_Tusers",method=RequestMethod.GET)
	    public ModelAndView manager_del_Tusers(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
	    	Map<String, Object> paraMap = WebUtils.getParametersStartingWith(request, "");
	    	int flag = usersService.findUserPart(paraMap);
	    	if(flag == 0){
	    		usersService.manager_del_tusers(paraMap);	    		
	    	}
	    	return new ModelAndView("redirect:/manager/manager_tusers_list?currentpageno=1");
	    }
	    /**
	     * 编辑页面
	     * @param request
	     * @param response
	     * @param modelMap
	     * @return
	     */
	    @RequestMapping(value = "/manager_save_Tusers",method=RequestMethod.POST)    
	    public ModelAndView save(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap){
	    	Map<String, Object> paraMap = WebUtils.getParametersStartingWith(request, "");
	    	String id = String.valueOf(paraMap.get("id"));
	    	String account = String.valueOf(paraMap.get("account"));
	    	String password = String.valueOf(paraMap.get("password"));
	    	String name = String.valueOf(paraMap.get("name"));
	    	if(account.equals("")||password.equals("")||name.equals("")){
	    		modelMap.addAttribute("account", "");
	    		modelMap.addAttribute("password", "");
	    		return new ModelAndView("users/user_add");
	    	}
	    	if(StringUtils.isEmpty(id)){
	    		Map<String, Object> map = usersService.findUsers(account);
	    		if(map==null || map.size()==0){
	    			usersService.manager_insert_tusers(paraMap);	    			
	    		}
	    	}else{
	    		usersService.manager_update_tusers(paraMap);
	    	}
	    	return new ModelAndView("redirect:/manager/manager_tusers_list?currentpageno=1");
	    }

}
